import {
  IGetWorkflowApprovalHistoryApprovalProcessInstanceIdV2ByProcessInstanceIdRes,
  getWorkflowApprovalHistoryApprovalProcessInstanceIdV2ByProcessInstanceId,
  postWorkflowApprovalTaskComplete
} from '@/api';
import { MciButton, MciDialog } from '@/components/base';
import { VitalFormV2, createFormV2, createVitalFormV2Ref } from 'vital';
import { useMode } from '../../approval-helper/useMode';
import { TApprovalConclusion } from '@/hooks/useCurrentTaskInfo';
import { useAppStore } from '@/store/app';
import { switchTab } from '@/utils/mini-bridge';
import './index.scss';
function getTaskId(data: IGetWorkflowApprovalHistoryApprovalProcessInstanceIdV2ByProcessInstanceIdRes) {
  const appStore = useAppStore();
  const taskId = (function () {
    let taskId = '';
    if (!data?.taskActivities?.length) return taskId;
    const { taskActivities, historicProcessInstance } = data;
    // 不是审批中状态直接返回空
    if (historicProcessInstance?.approvalConclusion !== 'PROCESSING') return taskId;

    taskActivities?.forEach((item) => {
      item.userTasks?.forEach((task) => {
        const { approvalStatus, assigneeUsers, id } = (task || {}) as any;

        // 审批中的任务
        if (!approvalStatus && assigneeUsers) {
          assigneeUsers.forEach((user) => {
            const isHandler = appStore.mcisaas.userId === user.userId;
            /* 避免被后面的任务覆盖 && 当前审批的操作人 */
            if (!taskId && isHandler) {
              taskId = id || '';
            }
          });
        }
      });
    });
    return taskId;
  })();

  return taskId;
}
export default defineComponent({
  props: {
    processInst: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const visible = ref(false);
    const formRef = createVitalFormV2Ref();
    const taskId = ref('');
    const confirmLoading = ref(false);
    const { initMode, approvalMode } = useMode();
    approvalMode.value = 'view';
    const showDialog = async () => {
      visible.value = true;
    };

    // 获取审批节点信息
    const getApprovalProgress = () => {
      if (!props.processInst) return;
      return getWorkflowApprovalHistoryApprovalProcessInstanceIdV2ByProcessInstanceId({
        processInstanceId: props.processInst
      }).then((res) => {
        taskId.value = getTaskId(res);
        initMode(res.historicProcessInstance?.approvalConclusion as TApprovalConclusion, res);
      });
    };

    const onSuccess = () => {
      approvalMode.value = 'view';
      switchTab('/pages/todo/index');
    };
    const formConfig = createFormV2<{ comment: string }>({
      attrs: {},
      mode: 'edit',
      formItems: [
        {
          attrs: {
            label: ''
          },
          rulePresets: ['required'],
          fields: [
            {
              type: 'input',
              prop: 'comment',
              attrs: {
                placeholder: '请输入驳回原因',
                type: 'textarea',
                rows: 4,
                class: 'mobile-textarea-bg'
              }
            }
          ]
        }
      ]
    });
    /* 通过 */
    const handleAgree = () => {
      confirmLoading.value = true;
      postWorkflowApprovalTaskComplete({
        taskId: taskId.value,
        comment: '',
        approvalStatus: 'AGREE'
      })
        .then(() => {
          onSuccess();
        })
        .finally(() => {
          confirmLoading.value = false;
        });
    };
    /* 驳回 */
    const handleReject = async (loadingCb: TAnyFunction) => {
      await formRef.value?.validate();
      const comment = formRef.value?.getModel()?.comment || '';
      loadingCb(true);
      await postWorkflowApprovalTaskComplete({
        taskId: taskId.value,
        comment,
        approvalStatus: 'REJECT'
      }).finally(() => {
        loadingCb(false);
      });
      onSuccess();
    };

    getApprovalProgress();

    return () => {
      if (approvalMode.value === 'edit') {
        return (
          <div class="flex h-60">
            <MciButton class="flex-1 h-48" onClick={showDialog}>
              驳回
            </MciButton>
            <MciButton loading={confirmLoading.value} type="primary" class="flex-1 h-48 " onClick={handleAgree}>
              同意
            </MciButton>
            <MciDialog
              fullscreen={false}
              v-model={visible.value}
              title={'驳回原因'}
              width="784px"
              confirmHandle={handleReject}>
              <VitalFormV2 ref={formRef} config={formConfig.value} />
            </MciDialog>
          </div>
        );
      }
      return null;
    };
  }
});
